package com.cqkjxy.commons.utils;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Calendar;
import java.util.Date;

public final class DateUtils {
    /**
     * 计算调休，请假，出差等时间差
     * @param
     * @return
     */
    public static Integer toDifferentDays(Date date1,Date date2){

        if (date1 == null && date2 == null){
            return null;
        }
        Calendar calendar1 = Calendar.getInstance();
        calendar1.setTime(date1);
        Calendar calendar2 = Calendar.getInstance();
        calendar2.setTime(date2);
        Integer day1 = calendar1.get(Calendar.DAY_OF_YEAR);
        Integer day2 = calendar2.get(Calendar.DAY_OF_YEAR);
        Integer year1 = calendar1.get(Calendar.YEAR);
        Integer year2 = calendar2.get(Calendar.YEAR);
        if (year1 != year2){//同一年

            int timeDistance = 0;
            for (int i = year1;i < year2;i++){

                if (i%4 ==0 && i%100 == 0 || i%400 == 0){//闰年
                    timeDistance += 366;
                }else {//不是闰年
                    timeDistance += 365;
                }
            }
            return timeDistance + (day2 - day1);
        }else {//不同年
            return day2 - day1;
        }
    }

    public static LocalDate toLocalDate(Date date) {
        if (date == null) {
            return null;
        }

        return date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
    }

    public static LocalDateTime toLocalDateTime(Date date) {
        if (date == null) {
            return null;
        }

        return date.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
    }

    public static Date toDate(LocalDate date) {
        if (date == null) {
            return null;
        }

        return Date.from(date.atStartOfDay(ZoneId.systemDefault()).toInstant());
    }

    public static Date toDate(LocalDateTime date) {
        if (date == null) {
            return null;
        }

        return Date.from(date.atZone(ZoneId.systemDefault()).toInstant());
    }
}
